$(document).on('pageinit', function(){
	var studentId = getCookie('studentId');
	var year = getCookie('year');
	var term = getCookie('term');
	if(!/\d{10}/.test(studentId)){
		$('#warningText').text('学号不正确，请返回重新输入');
		$('#warningBtn').click();
	}
	else if(!/20\d{2}-20\d{2}/.test(year)){
		$('#warningText').text('学年不正确，请返回重新选择');
		$('#warningBtn').click();
	}
	else if(!/\d{1}/.test(year)){
		$('#warningText').text('学期不正确，请返回重新选择');
		$('#warningBtn').click();
	}
	else{
		//console.log('&xh='+studentId+'&xn='+year+'&xq='+term);
		$.ajax({
			url: './php/get_grade.php',
			type: 'GET',
			data: '&xh='+studentId+'&xn='+year+'&xq='+term,
			dataType: "JSON",
			success:
				function(data){
					//console.log(data);
					hideLoader();
					if(data.error){
						$('#warningText').text(data.error);
						$('#warningBtn').click();
					}else{
						$('#name').text(data.name+'同学的成绩');
						for(var i in data.grade){
							var gua = getCookie(studentId+data.grade[i][5].replace(/-|\(|\)/g, ''));
							if(gua){
								$('#gradeList').append('<li class="showPS" data-ps="'+data.grade[i][1]+'">'+data.grade[i][4]+'<span class="ui-li-count">'+data.grade[i][3]+'</span></li>').find("li:last").hide();
							}else{
								$('#gradeList').append('<li><a class="showGrade" href="#" data-grade="'+data.grade[i][3]+'" data-xkkh="'+data.grade[i][5].replace(/-|\(|\)/g, '')+'">'+data.grade[i][4]+'<span class="ui-li-count" data-xkkh="'+data.grade[i][5].replace(/-|\(|\)/g, '')+'">刮一刮</span></a></li>').find("li:last").hide();
							}
							$("#gradeList").listview('refresh');
							$("#gradeList").find("li:last").slideDown(300); 
						}
						$('.showGrade').on('tap', function(){
							var grade = $(this).data('grade');
							var xkkh = $(this).data('xkkh');
							$('#title').text('成绩刮刮乐');
							$('#grade').scratchie({
								target : 'target',
								img : './php/get_num.php?num='+grade,
								imgHeight : 200, 
								imgWidth : 200,
								title : '刮一刮',
								fillImg : './php/blank.jpg',
								requireMouseClick : false,
								completion: 30,
								callback: function(){
									//alert(xkkh);
									setCookie(studentId+xkkh, grade);
								}
							});
							$('#guaBtn').click();
						});
						$('.showPS').on('tap', function(){
							var grade = $(this).data('ps');
							$('#target').attr('src', './php/get_num.php?num='+grade);
							$('#title').text('平时分');
							$('#guaBtn').click();
						});
					}
				}
		});
	}
});

$(document).on('pagechange', function(){
	$('.ui-li-count').each(function(i, e){
		var xkkh = studentId+$(this).data('xkkh');
		var grade = getCookie(xkkh);
		//alert(grade);
		if(grade)
			$(e).text(grade);
	});
});

$(document).ready(function(){
	showLoader();
});